# Create your awesome net!!
import sys, os

import matplotlib.pyplot as plt

sys.path.append(os.pardir)  # 为了导入父目录的文件而进行的设定
import pickle
import numpy as np
from collections import OrderedDict
from neural_net_classify.common.layers import *

class ConvNet:
    def __init__(self, input_dim=(3, 60, 30),
                 conv_param_1={'filter_num': 6, 'filter_size': 3, 'pad': 1, 'stride': 1},#这一层卷积层出来的形状为9*60*30
                                                                                        #经过maxpolling 变成9*30*15
                 conv_param_2={'filter_num': 1, 'filter_size': 3, 'pad': 0, 'stride': 3},#这一层卷积层出来的形状为1*10*5
                 output_size=4):
        # 初始化权重===========
        # 各层的神经元平均与前一层的几个神经元有连接（TODO:自动计算）
        pre_node_nums = np.array(
            [6 * 3 * 3, 1 * 3 * 3 ,1 * 10*5])#决定了w的形状

        wight_init_scales = np.sqrt(2.0 / pre_node_nums)  # 使用ReLU的情况下推荐的初始值

        self.params = {}
        pre_channel_num = input_dim[0]
        for idx, conv_param in enumerate(
                [conv_param_1,conv_param_2]):
            self.params['W' + str(idx + 1)] = wight_init_scales[idx] * np.random.randn(conv_param['filter_num'],
                                                                                       pre_channel_num,
                                                                                       conv_param['filter_size'],
                                                                                       conv_param['filter_size'])
            self.params['b' + str(idx + 1)] = np.zeros(conv_param['filter_num'])
            pre_channel_num = conv_param['filter_num']
        self.params['W3'] = wight_init_scales[2] * np.random.randn(pre_node_nums[2], output_size)
        self.params['b3'] = np.zeros(output_size)

        # 生成层===========
        self.layers = []
        self.layers.append(Convolution(self.params['W1'], self.params['b1'],
                                       conv_param_1['stride'], conv_param_1['pad']))
        self.layers.append(Relu())
        self.layers.append(Pooling(2,2,stride=2))
        self.layers.append(Convolution(self.params['W2'], self.params['b2'],
                                       conv_param_2['stride'], conv_param_2['pad']))
        self.layers.append(Dropout(0.5))
        self.layers.append(Relu())
        self.layers.append(Affine(self.params['W3'], self.params['b3']))
        self.layers.append(Relu())
        self.last_layer = SoftmaxWithLoss()

    def predict(self, x, train_flg=False):
        for layer in self.layers:
            if isinstance(layer, Dropout):
                x = layer.forward(x, train_flg)
            else:
                x = layer.forward(x)
        return x

    def loss(self, x, t):
        y = self.predict(x, train_flg=True)
        return self.last_layer.forward(y, t)

    def accuracy(self, x, t, batch_size=30):
        if t.ndim != 1: t = np.argmax(t, axis=1)

        acc = 0.0

        for i in range(int(x.shape[0] / batch_size)):
            tx = x[i * batch_size:(i + 1) * batch_size]
            tt = t[i * batch_size:(i + 1) * batch_size]
            y = self.predict(tx, train_flg=False)
            y = np.argmax(y, axis=1)
            acc += np.sum(y == tt)

        return acc / (x.shape[0] // batch_size)/batch_size

    def show_wrong_data(self, x, t, batch_size=1201):
        if t.ndim != 1: t = np.argmax(t, axis=1)

        acc = 0.0

        for i in range(int(x.shape[0] / batch_size)):
            tx = x[i * batch_size:(i + 1) * batch_size]
            tt = t[i * batch_size:(i + 1) * batch_size]
            y = self.predict(tx, train_flg=False)
            y = np.argmax(y, axis=1)
            index=np.where(y != tt)
            if (len(index)!=0):
                for j in range(len(index)):
                    #print(tx[index[j]].squeeze().transpose(1,2,0).shape)
                    plt.imsave('C:/Users/caixiaofeng/Desktop/triple_town_with_cnn/wrong_data/'+str(i)+str(j)+'.jpg',tx[index[j]].squeeze().transpose(1,2,0))
            acc += np.sum(y == tt)
        return acc / (x.shape[0] // batch_size)/batch_size

    def gradient(self, x, t):
        # forward
        self.loss(x, t)

        # backward
        dout = 1
        dout = self.last_layer.backward(dout)

        tmp_layers = self.layers.copy()
        tmp_layers.reverse()
        for layer in tmp_layers:
            dout = layer.backward(dout)

        # 设定
        grads = {}
        for i, layer_idx in enumerate((0, 3,6)):
            grads['W' + str(i + 1)] = self.layers[layer_idx].dW
            grads['b' + str(i + 1)] = self.layers[layer_idx].db

        return grads

    def save_params(self, file_name="params.pkl"):
        params = {}
        for key, val in self.params.items():
            params[key] = val
        with open(file_name, 'wb') as f:
            pickle.dump(params, f)

    def load_params(self, file_name="params.pkl"):
        with open(file_name, 'rb') as f:
            params = pickle.load(f)
        for key, val in params.items():
            self.params[key] = val

        for i, layer_idx in enumerate((0, 3, 6)):
            self.layers[layer_idx].W = self.params['W' + str(i + 1)]
            self.layers[layer_idx].b = self.params['b' + str(i + 1)]